package com.auth.manager.service.dict.impl;

import com.auth.manager.common.ex.BizException;
import com.auth.manager.mapper.dict.StandardCodeItemMapper;
import com.auth.manager.pojo.dict.StandardCode;
import com.auth.manager.pojo.dict.StandardCodeItem;
import com.auth.manager.service.dict.StandardCodeItemService;
import com.auth.manager.utils.DateTimeUtil;
import com.auth.manager.utils.page.PageUtil;
import com.auth.manager.utils.page.PageVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @version 1.0.0
 * @Date: 2022/5/12 16:52
 * @Author ZhuYouBin
 * @Description 标准代码数据项
 */
@Service
public class StandardCodeItemServiceImpl extends ServiceImpl<StandardCodeItemMapper, StandardCodeItem> implements StandardCodeItemService {

    @Autowired
    private StandardCodeItemMapper standardCodeItemMapper;

    @Override
    public void createCodeItem(StandardCodeItem standardCodeItem) {
        // 判断标准代码是否存在
        QueryWrapper<StandardCodeItem> wrapper = new QueryWrapper<>();
        wrapper.eq("value", standardCodeItem.getValue());
        wrapper.last("limit 1");
        long count = this.count(wrapper);
        if (count > 0) {
            throw new BizException("标准代码已经存在");
        }

        standardCodeItem.setDeleted("01");
        standardCodeItem.setCreateTime(DateTimeUtil.currentDateTime());
        // 新增
        this.save(standardCodeItem);
    }

    @Override
    public void removeCodeItem(String id) {
        StandardCodeItem codeItem = this.getById(id);
        if (!Optional.ofNullable(codeItem).isPresent()) {
            throw new BizException("分类不存在");
        }
        codeItem.setDeleted("02");
        this.updateById(codeItem);
    }

    @Override
    public void updateCodeItem(StandardCodeItem standardCodeItem) {
        // 判断标准代码是否存在
        QueryWrapper<StandardCodeItem> wrapper = new QueryWrapper<>();
        wrapper.eq("value", standardCodeItem.getValue());
        wrapper.ne("id", standardCodeItem.getId());
        wrapper.last("limit 1");
        long count = this.count(wrapper);
        if (count > 0) {
            throw new BizException("标准代码已经存在");
        }
        // 更新
        this.save(standardCodeItem);
    }

    @Override
    public List<StandardCode> getStandardCode(String typeCode) {
        StandardCode standardCode = new StandardCode();
        standardCode.setTypeCode(typeCode);
        return standardCodeItemMapper.queryStandardCode(standardCode);
    }

    @Override
    public PageVo queryPage(PageVo pageVo, StandardCodeItem standardCodeItem) {
        PageUtil.start(pageVo);
        List<StandardCodeItem> list = this.list();
        return PageUtil.end(list);
    }
}
